package com.corecmd.tcloud.tcim.utils;

import com.corecmd.tcloud.tcimcommon.im.common.PacketCodeC;
import com.corecmd.tcloud.tcimcommon.im.domain.MessageRequestPacket;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author : TianShaoJiao
 * @date : 2021/2/20
 * @description :
 **/
public class ImSessionHolder {
    public static final Map<String, NioSocketChannel> SESSIONHOLDERS = new ConcurrentHashMap<String, NioSocketChannel>(2);
    public static void put(String sessionId,NioSocketChannel channel){
        SESSIONHOLDERS.put(sessionId,channel);
    }
    public static void delete(String sessionId){
        Iterator<String> it = SESSIONHOLDERS.keySet().iterator();
        while (it.hasNext()){
            String key = it.next();
            if (key.equalsIgnoreCase(sessionId)){
                it.remove();
            }
        }
    }
    public static NioSocketChannel get(String sessionId){
        return SESSIONHOLDERS.get(sessionId);
    }

    public static boolean sendMessage(String senderId,MessageRequestPacket messageRequestPacket){
        boolean isSuccess = false;
        try {
            NioSocketChannel channel = get(senderId);
            if (null != channel && messageRequestPacket != null){
                // 编码
                ByteBuf buffer = new PacketCodeC().encode(messageRequestPacket);
                // 写数据
                channel.writeAndFlush(buffer).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        System.out.println("客户端:"+senderId+"发送消息是否成功："+isSuccess);
                    }
                });
            } else {
                System.out.println("没有查询到im连接信息："+senderId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isSuccess;
    }
}
